import { SearchAction } from '@/types/store.d'
import { History, Result, Suggestion } from '@/types/data'
import { getLocalHistories } from '@/utils/search'

type SearchState = {
  suggestion: Suggestion
  histories: History
  results: Result[]
}

const initialState = {
  suggestion: [],
  histories: getLocalHistories(),
  results: []
} as SearchState

export default function searchReducer(
  state = initialState,
  action: SearchAction
) {
  if (action.type === 'search/set_suggestion') {
    return {
      ...state,
      suggestion: action.payload
    }
  }

  if (action.type === 'search/set_history') {
    return {
      ...state,
      histories: action.payload
    }
  }

  if (action.type === 'search/clear_history') {
    return {
      ...state,
      histories: []
    }
  }

  if (action.type === 'search/set_results') {
    return {
      ...state,
      results: action.payload
    }
  }

  return state
}
